/*********************************************************************************
  *Copyright (c)    2021   xldeng
  *FileName:        297b.cpp.c
  *Author:          xldeng
  *Version:         1.0
  *Date:            2021/2/16 9:22
  *Description:     
  *Others:          
  *Function List:   
     1.…………
  *History:  
     1.Date:
       Author:
       Modification:
**********************************************************************************/
#include "../header.h"

class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode *root) {
        string ans;
        serialize(root, ans);
        return ans;
    }

    // Decodes your encoded data to tree.
    TreeNode *deserialize(string data) {
        stringstream input(data);
        list<string> nodes;
        string tmp;
        while (getline(input, tmp, ','))
            nodes.emplace_back(tmp);
        return deserialize(nodes);
    }

private:
    string SEP = ",";
    string NULL_STRING = "#";

    void serialize(TreeNode *root, string &ans) {
        if (root == nullptr) {
            ans.append(NULL_STRING).append(SEP);
            return;
        }
        ans.append(to_string(root->val)).append(SEP);
        serialize(root->left, ans);
        serialize(root->right, ans);
    }

    TreeNode *deserialize(list<string> &nodes) {
        if (nodes.empty())
            return nullptr;
        string first = nodes.front();
        nodes.pop_front();
        TreeNode * root = new TreeNode(stoi(first));
        root->left = deserialize(nodes);
        root->right = deserialize(nodes);
        return root;
    }
};
